<template>
  <view>
    <view class="page-body">
      <view class="page-section page-section-gap" style="text-align: center;">
        <button type="default" @click="doPlay()">播放</button>
        <button type="default" @click="doPause()">暂停</button>
        当前播放时间：{{currentTime}}/{{duration}}
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        currentTime: "00:00",
        duration: "00:00"
      };
    },
    onLoad() {
      this.timer = null;
      this.innerAudioContext = uni.createInnerAudioContext();
      this.innerAudioContext.onCanplay(() => {
        this.innerAudioContext.duration;
        setTimeout(() => {
          this.duration = this.formatSeconds(this.innerAudioContext.duration)
        }, 300)
      });
      this.innerAudioContext.onPlay(() => {
        this.timer = setInterval(() => {
          this.currentTime = this.formatSeconds(this.innerAudioContext.currentTime)
        }, 1000)
      })
    },
    onUnload() {
      clearInterval(this.timer);
      this.innerAudioContext.destroy();
    },
    methods: {
      doPlay() {
        this.innerAudioContext.src = "http://www.lucklnk.com/music/jiehun/1.mp3"
        this.innerAudioContext.play();
      },
      doPause() {
        this.innerAudioContext.pause();
        clearInterval(this.timer);
      },
      formatSeconds(value) {
        let minute = parseInt(value / 60);
        let second = parseInt(value % 60);
        if (minute < 10) {
          minute = "0" + minute;
        }
        if (second < 10) {
          second = "0" + second;
        }
        return minute + ":" + second;
      }
    }
  }
</script>

<style lang="scss">

</style>